<%@page language="java" session="true" 
import="java.io.*,java.util.*,java.io.*,java.sql.*,javax.servlet.*,java.text.*,Database.DBConnection"%> 

<%
String SelectedPNVar=request.getParameter("PN");
String ProcedureNameVar=request.getParameter("ProcedureName");
String CodeVar=request.getParameter("Code");
String CategoryVar=""; 

while(CodeVar.indexOf(" ")!=-1)
{
	int indexVar=CodeVar.indexOf(" ");
	CodeVar = CodeVar.substring(0,indexVar)+CodeVar.substring(indexVar+1);
}

String EffectiveDateVar=request.getParameter("EDate").toString();
String reformattedStr="";

SimpleDateFormat odf = new SimpleDateFormat("dd MMM yy");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
reformattedStr = sdf.format(odf.parse(EffectiveDateVar));
System.out.println(reformattedStr);

try
{
String connectionURL1st = "jdbc:mysql://localhost:3306/qmsdb";
Connection connection1st = null;
Statement statement1st = null;
ResultSet rs1st = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection1st = DBConnection.connect(true);
statement1st = connection1st.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
String QueryString1st = "SELECT Category from qmsdb.processes WHERE ProcessName='"+SelectedPNVar+"'";
rs1st = statement1st.executeQuery(QueryString1st);

while (rs1st.next())
{
	CategoryVar=rs1st.getString("Category");
}			 

// close all the connections.
rs1st.close();
statement1st.close();
connection1st.close();
}
catch(Exception ex)
{
}
finally
{
}

String contentType = request.getContentType();
//here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
	if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
		DataInputStream in = new DataInputStream(request.getInputStream());
		//we are taking the length of Content type data
		int formDataLength = request.getContentLength();
		byte dataBytes[] = new byte[formDataLength];
		int byteRead = 0;
		int totalBytesRead = 0;
		//this loop converting the uploaded file into byte code
		while (totalBytesRead < formDataLength) {
			byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
			totalBytesRead += byteRead;
			}

		String file = new String(dataBytes);
		//for saving the file name
		String saveFile = file.substring(file.indexOf("filename=\"") + 10);
		saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
		saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
		int lastIndex = contentType.lastIndexOf("=");
		String boundary = contentType.substring(lastIndex + 1,contentType.length());
		int pos;
		//extracting the index of file 
		pos = file.indexOf("filename=\"");
		pos = file.indexOf("\n", pos) + 1;
		pos = file.indexOf("\n", pos) + 1;
		pos = file.indexOf("\n", pos) + 1;
		int boundaryLocation = file.indexOf(boundary, pos) - 4;
		int startPos = ((file.substring(0, pos)).getBytes()).length;
		int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
		String root =  getServletConfig().getServletContext().getRealPath("/")+File.separator+"WordDoc_Proccesses/"+CategoryVar+"/"+ SelectedPNVar +"/Procedure/"+CodeVar+"/";   
		String root2="WordDoc_Proccesses/"+CategoryVar+"/"+ SelectedPNVar +"/Procedure/"+CodeVar+"/";				                  
		 File filePath = new File(root);

         if (!filePath.exists()) {
             filePath.mkdirs();
         }

		String LoadInto=root+saveFile;
		// creating a new file with the same name and writing the content in new file
		FileOutputStream fileOut = new FileOutputStream(LoadInto);
		fileOut.write(dataBytes, startPos, (endPos - startPos));
		fileOut.flush();
		fileOut.close();

 
	
		Connection con=null,con1=null; 
		PreparedStatement stmt=null,stmt1=null; 
		PreparedStatement ps=null,ps1=null; 
		ResultSet rs=null,rs1=null; 
		String sql="",sql1="",a=""; 
		con=DBConnection.connect(true);
		int j1=0; 
		
		try 
		{ 
			sql="INSERT INTO processes (ProcessName, Code, ProcedureName, ProcedureURL, ProcLastUpdate, Category) Values (?, ?, ?, ?, ?, ?)"; 
			stmt = con.prepareStatement(sql);
			stmt.setString(1, SelectedPNVar);
			stmt.setString(2, CodeVar);
			stmt.setString(3, ProcedureNameVar);
			stmt.setString(4, root2+saveFile);
			stmt.setString(5, reformattedStr);
			stmt.setString(6, CategoryVar);
			j1=stmt.executeUpdate(); 
		if(j1!=0) 
		{ 
		%> 
		<script type="text/javascript"> 
	
			alert('File successfully uploaded!\nYou will be directed back to the previous page once you click "OK"'); 
			window.location="Proc_NewProcedure.jsp";
			
		</script> 
		<% 

		} 

		} 
		catch(Exception ex) 
		{ 
			ex.printStackTrace(); 
		} 

		} 
		%>	
